export const randomInt = (n) => {
  return Math.floor(Math.random() * n);
}

export const generateRandomMarkerId = (min = 10000, max = 10000000) => {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}
export const obj2Str = obj => {
  let t = Object.keys(obj).reduce((prev, next) => {
    prev = prev + next + '=' + obj[next] + '&'
    return prev
  }, '?')
  t = t.slice(0, -1) //去掉最后一个&
  return t
}

export const obj2Arr = obj => {
  return Object.keys(obj).reduce((prev, next) => {
    prev.push({ name: next, value: obj[next] })
    return prev
  }, [])
}

const diff = date => {
  const today = new Date();

  const tomorrow = new Date();
  tomorrow.setDate(today.getDate() + 1);

  const yesterday = new Date();
  yesterday.setDate(today.getDate() - 1);

  const currentYear = today.getFullYear();
  const currentMonth = today.getMonth();
  const currentDay = today.getDate();

  const currentYear_tomorrow = tomorrow.getFullYear();
  const currentMonth_tomorrow = tomorrow.getMonth();
  const currentDay_tomorrow = tomorrow.getDate();


  const currentYear_yesterday = yesterday.getFullYear();
  const currentMonth_yesterday = yesterday.getMonth();
  const currentDay_yesterday = yesterday.getDate();

  const checkedYear = date.getFullYear();
  const checkedMonth = date.getMonth();
  const checkedDay = date.getDate();
  return {
    isToday: currentYear === checkedYear && currentMonth === checkedMonth && currentDay === checkedDay,
    isTomorrow: currentYear_tomorrow === checkedYear && currentMonth_tomorrow === checkedMonth && currentDay_tomorrow === checkedDay,
    isYesterday: currentYear_yesterday === checkedYear && currentMonth_yesterday === checkedMonth && currentDay_yesterday === checkedDay
  }

}

/**
 * 
 */
export const roundToNDecimal = (num, n) => {
  let multiplier = Math.pow(10, n);
  let rounded = Math.round(num * multiplier) / multiplier;
  return rounded;
}

const weeks = ['周日', '周一', '周二', '周三', '周四', '周五', '周六',]
export const formatDate = (date, formatFn) => {
  if (typeof formatFn !== 'function') throw new Error('必须传入格式化函数')
  const cur = date ? new Date(date) : new Date()
  const dateInfo = {
    year: cur.getFullYear().toString(),
    month: (cur.getMonth() + 1).toString().padStart(2, '0'),
    day: cur.getDate().toString().padStart(2, '0'),
    hour: cur.getHours().toString().padStart(2, '0'),
    minute: cur.getMinutes().toString().padStart(2, '0'),
    second: cur.getSeconds().toString().padStart(2, '0'),
    week: weeks[cur.getDay()],
    isToday: false,
    isTomorrow: false,
    isYesterday: false
  }
  const { isToday, isTomorrow, isYesterday } = diff(cur)
  dateInfo.isToday = isToday
  dateInfo.isTomorrow = isTomorrow
  dateInfo.isYesterday = isYesterday


  return formatFn(dateInfo)

}


export function debounce(func, delay = 500) {
  let timer;
  return function (...args) {
    clearTimeout(timer);
    timer = setTimeout(() => {
      func.apply(this, args);
    }, delay);
  };
}
